import { DbfReader } from './index.js'
import { dataTableProto } from '../data'
import {DataTable} from '../data'

function importDbfTable(buf, o) {
  const opts = o || {}
  return new ShapefileTable(buf, opts.encoding)
}
extend(ShapefileTable.prototype, dataTableProto)
function ShapefileTable(buf, encoding) {
  let reader = new DbfReader(buf, encoding)
  let altered = false
  let table = null
  function getTable() {
    if (!table) {
      table = new DataTable(reader.readRows())
      reader = null
      buf = null
    }
    return table
  }
  this.exportAsDbf = function(opts) {
    // export original dbf bytes if possible, for performance
    const useOriginal = !!reader && !altered && !opts.field_order && !opts.encoding
    return useOriginal ? reader.getBuffer() : getTable().exportAsDbf(opts)
  }
  this.getReadOnlyRecordAt = function(i) {
    return reader ? reader.readRow(i) : table.getReadOnlyRecordAt(i)
  }
  this.deleteField = function(f) {
    if (table) {
      table.deleteField(f)
    } else {
      altered = true
      reader.deleteField(f)
    }
  }
  this.getRecords = function() {
    return getTable().getRecords()
  }
  this.getFields = function() {
    return reader ? reader.getFields() : table.getFields()
  }
  this.size = function() {
    return reader ? reader.size() : table.size()
  }
}
function extend(o) {
  const dest = o || {}
  const n = arguments.length
  for (let i = 1; i < n; i += 1) {
    let src = arguments[i] || {}
    for (let key in src) {
      if (src.hasOwnProperty(key)) {
        dest[key] = src[key]
      }
    }
  }
  return dest
}
export {
  ShapefileTable,
}
export default {
  importDbfTable,
}